<?php

namespace Trawind\Helpers;

use Trawind\Basics\Traits\HasFactory;

class WechatHelper
{

    use HasFactory;

    const BUG_BOT = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=43602053-be50-48f1-b223-ad4564fd956c';

    const VERSION_BOT = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6f6c1514-83e2-4839-80d9-e180dc379edc';

    const LADENG_BOT = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=985bd503-0acb-45a2-994b-3c8432f04e27';

    public $developer = [
        'account' => ['18201177163', '15950634415'],
        'user' => [],
        'product' => ['15665420815', '18201177163'],
        'finance' => ['15021769391'],
        'purchase' => ['15021769391'],
        'storage' => ['18201177163'],
        'report' => ['15950634415'],
        'sale' => ['17349756586'],
        'inventory' => ['18201177163'],
        'notification' => ['15061690110'],
        'operation' => ['15665420815'],
        'extension' => ['15665420815'],
    ];

    private $appName;

    private $appEnv;

    private $guzzle;

    private $bot;

    public function __construct(?string $bot = null)
    {
        $this->bot = $bot ?? static::BUG_BOT;
        $this->appName = config('app.name');
        $this->appEnv = config('app.env');
        $this->guzzle = HttpClientHelper::guzzle();
    }


    /**
     *   Push system exceptions to wechat
     *
     * @param  string  $message
     * @param  int     $code
     * @param          $trace
     * @param  string  $exception
     * @return $this
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function systemExceptionNotice(string $message, int $code, $trace = '', string $exception = ''): self
    {
        $url = SystemHelper::runningInConsole() ? '[console]' : urldecode(url()->full());
        $content = "# 有报错，请注意。
>环境：<font color=\"info\">".$this->appEnv."</font>
>服务：<font color=\"info\">".$this->appName."</font>
>路由：<font color=\"comment\">(".request()->method().")</font>```".$url."```
>异常：<font color=\"warning\">".addslashes($exception)."</font>
>错误码：<font color=\"comment\">".$code."</font>
>错误：<font color=\"warning\">".substr(addslashes($message), 0, 700)."</font>
>trace：".(is_array($trace) ? json_encode($trace) : $trace);

        return $this->pushMessage([
            'msgtype' => 'markdown',
            'markdown' => [
                'content' => substr($content, 0, 4000).'...'
            ]
        ]);
    }


    /**
     *  Push system exceptions to wechat
     *
     * @param  string  $message
     * @param  string  $trace
     * @return $this
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function migrateExceptionNotice(string $message, string $trace = ''): self
    {
        $content = "# 警报警报，一级警报！数据迁移有问题。
>环境：<font color=\"info\">".$this->appEnv."</font>
>服务：<font color=\"info\">".$this->appName."</font>
>错误：<font color=\"warning\">".substr(addslashes($message), 0, 1000)."</font>
>trace：".$trace;

        return $this->pushMessage([
            'msgtype' => 'markdown',
            'markdown' => [
                'content' => substr($content, 0, 4000).'...'
            ]
        ]);
    }


    /**
     *  Push queue exception to wechat
     *
     * @param  string  $jobClass
     * @param  string  $message
     * @return $this
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function queueExceptionNotice(string $jobClass, string $message): self
    {
        $data = [
            'msgtype' => 'markdown',
            'markdown' => [
                'content' => "爆炸爆炸，mq异常，请注意。
>环境：<font color=\"info\">".$this->appEnv."</font>
>服务：<font color=\"info\">".$this->appName."</font>
>job：<font color=\"warning\">".addslashes($jobClass)."</font>
>错误：<font color=\"comment\">".$message."</font>"
            ]
        ];

        return $this->pushMessage($data);
    }

    /**
     *  Release notice to wechat
     *
     * @param  array  $version
     * @return $this
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function versionReleaseNotice(array $version): self
    {
        $data = [
            'msgtype' => 'markdown',
            'markdown' => [
                'content' => "# 新版本计划来袭
>环境：<font color=\"info\">".$this->appEnv."</font>
>版本号：<font color=\"info\">".$version['number']."</font>
>发布时间：<font color=\"warning\">".$version['release_at']."</font>
>发布内容：```".strip_tags($version['content'])."```"
            ]
        ];

        return $this->pushMessage($data);
    }


    /**
     * In WeChat @Developer
     */
    public function withDeveloper()
    {
        $this->pushMessage([
            'msgtype' => 'text',
            'text' => [
                'content' => $this->getRandomPoetry(),
                "mentioned_mobile_list" => $this->developer[$this->appName] ?? ['@all']
            ]
        ]);
    }


    /**
     * Push message to wechat
     *
     * @param  array  $json
     * @return $this
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function pushMessage(array $json)
    {
        try {
            $response = $this->guzzle->post($this->bot, compact('json'));
            /*$content = HttpClientHelper::getResponseContent($response);
            if ($content['errmsg'] !== 'ok') {
                $this->guzzle->post(static::LADENG_BOT, [
                    'json' => [
                        'msgtype' => 'text',
                        'text' => [
                            'content' => $content['errmsg']
                        ]
                    ]
                ]);
            }*/
        } catch (\Exception $exception) {
        }

        return $this;
    }


    /**
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getRandomPoetry(): string
    {
        $poetry = '[炸弹][炸弹][炸弹]';
        if ($this->appEnv === 'develop') {
            try {
                $content = HttpClientHelper::getResponseContent($this->guzzle->get('https://v1.jinrishici.com/all'));
                $poetry = ($content['content'] ?? '').($content['author'] ?? '').'提醒您';
            } catch (\Exception $e) {
                $poetry = '哼。';
            }
        }

        return $poetry.' please look look ↑↑↑';
    }

}